package edu.com.wjt219971332.controller;

import edu.com.wjt219971332.entity.User;
import edu.com.wjt219971332.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("login")
public class loginController {
    @Autowired
    private UserService userService;
    @RequestMapping("/loginInit")
    public String loginInit(){
        return "user/login";
    }
    @RequestMapping("/loginshow")
    public String loginshow(){
        return "user/adminshow";
    }

    @RequestMapping("/loginshow2")
    public String loginshow2(){
        return "user/show";
    }
    @RequestMapping("/login")
    @ResponseBody
    public ResponseEntity<Map<String, String>> login(@RequestBody Map<String, String> data,
                                                     HttpServletRequest request) {
        String account = data.get("account");
        String password = data.get("password");
        User user = userService.findByName(account, password);
        Map<String, String> response = new HashMap<>();
        if(user == null) {
            response.put("message", "账号或密码错误");
            response.put("redirect", "login/loginInit");
            return ResponseEntity.ok(response);
        }
        // 登录成功后设置用户名到 session
        request.getSession().setAttribute("username", user.getUsername());
        request.getSession().setAttribute("userid", user.getUserid());
        request.getSession().setAttribute("userrole", user.getRole());
        if(user.getRole().equals("0"))  response.put("redirect", "loginshow");

        else if(user.getRole().equals("1") || user.getRole().equals("2")){
            response.put("redirect", "loginshow2");
        }
        else{
            response.put("redirect", "../login/loginInit");
        }
        return ResponseEntity.ok(response);
    }
    //退出登录
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        HttpSession httpSession = request.getSession();
        httpSession.invalidate();
        return "redirect:/login/loginInit";
    }
    @RequestMapping("/registerInit")
    public String registerInit(){
        return "user/insert";
    }

    @RequestMapping("/register")
    public String register(@ModelAttribute("user") User user){
        userService.insert(user);
        return "redirect: ../login/loginInit";
    }
}
